"""

和文件相关的类定义
"""
import json

from data_define import Record


# 顶层抽象类
class FileReader:
    def read_data(self) -> list[Record]:
        """读取文件的数据，读到的每一条数据都转换为Record对象，
        将他们都封装到list内部返回即可"""
        pass


class TextFileRead(FileReader):
    def __init__(self, path):
        # 定义成员变量记录文件的路径
        self.path = path

    # 复写（实现抽象方法）父类的方法
    def read_data(self) -> list[Record]:
        f = open(self.path, 'r', encoding='utf-8')
        record_list: list[Record] = []
        for i in f.readlines():
            # 消除每一行中的\n换行
            line = i.strip()
            data_list = line.split(',')
            record = Record(data_list[0], data_list[1], data_list[2], data_list[3])
            record_list.append(record)
        f.close()
        return record_list


class JsonFileReader(FileReader):
    def __init__(self, path):
        self.path = path

    def read_data(self) -> list[Record]:
        f = open(self.path, 'r', encoding='utf-8')
        record_list: list[Record] = []
        for i in f.readlines():
            data_dict = json.loads(i)
            record = Record(data_dict['date'], data_dict['order_id'], int(data_dict['money']), data_dict['province'])
            record_list.append(record)
        f.close()
        return record_list

